/* eslint-disable */
'use strict'

const express = require('express')
const path = require('path')
const favicon = require('serve-favicon')
const logger = require('morgan')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const session = require('express-session')

const log4js = require('log4js')
log4js.configure('./config/log4js.json')
const log = log4js.getLogger('server')

const ejs = require('ejs')
const env = process.env.NODE_ENV


const index = require('./routes/index')
const users = require('./routes/users')
const upload = require('./routes/upload')
const infos = require('./routes/queryInfos')
const exportExcel = require('./routes/exportExcel')
const addConsumer = require('./routes/addConsumer')
const searchConsumer = require('./routes/searchConsumer')
const email = require('./routes/email')

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.engine('.html', ejs.__express)
app.set('view engine', 'html')
app.use(express.static(path.join(__dirname, '../public')))

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
//Setup cookie parser and session
app.use(cookieParser())
app.use(session({
  name: 'genius-session.id',
  secret: 'theGlassInfo',
  cookie: {maxAge: 1000 * 60 * 60 * 24 * 3},
  rolling: true,
  resave: false,
  saveUninitialized: true
}))

app.use('/', index)
app.use('/api/users', users)
app.use('/api/upload', upload)
app.use('/api/queryInfos', infos)
app.use('/api/export', exportExcel)
app.use('/api/add', addConsumer)
app.use('/api/search', searchConsumer)
app.use('/api/email', email)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found')
  err.status = 404
  res.render('404')
  next(err)
})

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}

  // render the error page
  res.status(err.status || 500)
  res.render('error')
})

let port = env === 'dev' ? 3000 : 8080 

app.listen(port, () => {
  console.log('Server is launched. Listening at port', port)
  log.info('Server is launched. Listening at port', port)
})
